package cn.trigram.mgb;

import com.mysql.cj.jdbc.MysqlDataSource;
import java.util.Properties;
import javax.sql.DataSource;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import oracle.jdbc.pool.OracleDataSource;
import org.apache.commons.lang3.StringUtils;

@Slf4j
@Data
public class MybatisGeneratorProperties {

  private String javaModelGeneratorRootClass;

  private String javaClientGeneratorRootInterface;

  private Properties properties;

  private String contextId;

  private String targetRuntime;

  private String targetDirectory;

  private String targetPackage;

  private String jdbcDriverClass;

  private String jdbcConnectionURL;

  private String jdbcUserId;

  private String jdbcPassword;

  public MybatisGeneratorProperties(Properties properties) {

    this.properties      = properties;
    this.contextId       = this.properties.getProperty("contextId", "contextId");
    this.targetRuntime   = this.properties.getProperty("targetRuntime", "MyBatis3DynamicSql");
    this.targetDirectory = this.properties.getProperty("targetDirectory");
    this.targetPackage   = this.properties.getProperty("targetPackage");

    this.jdbcDriverClass                  = getPropertyAndValid("jdbc.driverClass");
    this.jdbcConnectionURL                = getPropertyAndValid("jdbc.connectionURL");
    this.jdbcUserId                       = getPropertyAndValid("jdbc.userId");
    this.jdbcPassword                     = getPropertyAndValid("jdbc.password");
    this.javaModelGeneratorRootClass      = this.properties.getProperty("javaModelGenerator.rootClass");
    this.javaClientGeneratorRootInterface = this.properties.getProperty("javaModelGenerator.rootClass");
  }

  private <T> T getPropertyAndValid(String key) {

    String val = this.properties.getProperty(key);
    if (StringUtils.isBlank(val)) {
      String errorMsg = String.format("生成器配置文件的key[%s]不能为空", key);
      log.error(errorMsg);
      throw new IllegalArgumentException(errorMsg);
    }
    return (T) val;
  }

  @SneakyThrows
  public DataSource getDataSource() {

    Thread.currentThread().getContextClassLoader().loadClass(this.getJdbcDriverClass());
    String jdbcDriverClass = this.getJdbcDriverClass();
    if (StringUtils.containsIgnoreCase(jdbcDriverClass, "mysql")) {
      MysqlDataSource dataSource = new MysqlDataSource();
      dataSource.setURL(this.getJdbcConnectionURL());
      dataSource.setUser(this.getJdbcUserId());
      dataSource.setPassword(this.getJdbcPassword());
      return dataSource;
    } else if (StringUtils.containsIgnoreCase(jdbcDriverClass, "oracle")) {
      OracleDataSource dataSource = new OracleDataSource();
      dataSource.setURL(this.getJdbcConnectionURL());
      dataSource.setUser(this.getJdbcUserId());
      dataSource.setPassword(this.getJdbcPassword());
      return dataSource;
    } else {
      throw new IllegalArgumentException("无数据源");
    }
  }

}
